import 'package:collection/collection.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_2b_client/apis/GoodsApi.dart';
import 'package:flutter_2b_client/components/LoadingButton.dart';
import 'package:flutter_hooks/flutter_hooks.dart';
import 'package:freezed_annotation/freezed_annotation.dart';

part 'GoodsUnitEditor.g.dart';

part 'GoodsUnitEditor.freezed.dart';

class GoodsUnitEditor extends HookWidget {
  final List<GoodsUnitFormData> value;
  final ValueChanged<List<GoodsUnitFormData>> onChange;

  const GoodsUnitEditor({Key? key, required this.value, required this.onChange})
      : super(key: key);

  @override
  Widget build(BuildContext context) {
    var basicUnit = useMemoized(() {
      return value.firstOrNull?.name;
    }, [value]);
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        SizedBox(
          width: 200,
          child: TextFormField(
            decoration:
                const InputDecoration(label: Text("单位"), hintText: "基本单位"),
            onChanged: (value) {
              var newList = this.value.toList();
              if (newList.isNotEmpty) {
                if(value.isEmpty && value.length==1){
                  newList.clear();
                }else {
                  newList[0] = newList[0].copyWith(name: value);
                }
              } else {
                newList.add(GoodsUnitFormData(name: value));
              }

              onChange(newList);
            },
            initialValue: basicUnit,
            readOnly: value.firstOrNull?.updatable == false,
          ),
        ),
        if (value.length > 1)
          ...value
              .sublist(1)
              .mapIndexed((index, e) => Row(
                    mainAxisAlignment: MainAxisAlignment.start,
                    crossAxisAlignment: CrossAxisAlignment.center,
                    children: [
                      Expanded(
                        child: TextFormField(
                          decoration: InputDecoration(
                            label: Text("辅助单位${index + 1}"),
                          ),
                          initialValue: e.name,
                          onChanged: (value) {
                            onChange(this.value.toList()
                              ..[index + 1] =
                                  this.value[index + 1].copyWith(name: value));
                          },
                          readOnly: !e.updatable,
                        ),
                      ),
                      const Padding(
                        padding: EdgeInsets.only(top: 18, left: 8, right: 8),
                        child: Text("="),
                      ),
                      Expanded(
                        child: TextFormField(
                          decoration: const InputDecoration(
                            hintText: "与基本单位的倍数",
                            label: Text(""),
                          ),
                          initialValue: e.basicMultiple.toString(),
                          onChanged: (value) {
                            onChange(this.value.toList()
                              ..[index + 1] = this.value[index + 1].copyWith(
                                  basicMultiple: int.tryParse(value) ?? 1));
                          },
                          readOnly: !e.updatable,
                          keyboardType: TextInputType.number,
                          validator: (value) {
                            if (value == null) {
                              return "请输入单位换算倍数";
                            }
                            if ((int.tryParse(value) ?? 1) < 1) {
                              return "请输入有效数字";
                            }
                            return null;
                          },
                        ),
                      ),
                      Padding(
                        padding: const EdgeInsets.only(top: 18, left: 8),
                        child: Text(basicUnit.toString()),
                      ),

                      Padding(
                        padding: const EdgeInsets.only(left: 8.0,top: 8),
                        child: Padding(
                          padding: const EdgeInsets.only(top: 8.0),
                          child: TextButton(onPressed: e.updatable?() {
                            onChange(value
                            .toList()
                            ..removeAt(index+1));
                          }:null,
                            child: Text("删除",style: TextStyle(color: Theme.of(context).colorScheme.error),),),
                        ),
                      )
                    ],
                  ))
              .toList(),
        if (basicUnit != null)
          Align(
            alignment: AlignmentDirectional.bottomEnd,
            child: TextButton(
              onPressed: () {
                onChange(
                    value.toList()..add(const GoodsUnitFormData(name: "",basicMultiple: 1)));
              },
              child: const Text("添加辅助单位"),
            ),
          ),
      ],
    );
  }
}

@freezed
class GoodsUnitFormData with _$GoodsUnitFormData {
  const factory GoodsUnitFormData(
      {int? id,
      required String name,
      @Default(0) int basicMultiple,
      @Default(true) bool updatable}) = _GoodsUnitFormData;

  const GoodsUnitFormData._();

  factory GoodsUnitFormData.fromJson(Map<String, dynamic> json) =>
      _$GoodsUnitFormDataFromJson(json);

  EditGoodsUnitRequest toRequest(){
    return EditGoodsUnitRequest(name: name, basicMultiple: basicMultiple, updatable: updatable,id:id);
  }
}
